package fun.qu_an.minecraft.fabric.fzbbl.handle;

import fun.qu_an.minecraft.fabric.fzbbl.FZBBL;
import net.minecraft.block.Blocks;
import net.minecraft.block.FacingBlock;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.ItemStack;
import net.minecraft.item.Items;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Direction;
import net.minecraft.world.World;

import java.util.HashMap;

public class PlayerPlacedHandle {
	public static void handle(PlayerEntity player, World world, BlockPos pos, ItemStack stack) {
		if (world.isClient) return; // 仅服务端

		// stack是调用该方法(ServerPlayerInteractionManager.interactBlock())时生效的物品
		// 判断玩家放的是不是活塞
		if (stack.getItem() != Items.PISTON) return;

		Direction pistonFacing = world.getBlockState(pos).get(FacingBlock.FACING);
		BlockPos bedrockPos = pos.offset(pistonFacing);
		if (world.getBlockState(bedrockPos).getBlock() != Blocks.BEDROCK) return;

		// 活塞缓存
		putPistonCaches(world, bedrockPos, player);
		// 日志
		FZBBL.LOGGER.debug("PlacedPistonFacingBedrock: {}, {}", pos, player);
	}

	private static void putPistonCaches(World world, BlockPos pos, PlayerEntity player) {
		FZBBL.PISTON_CACHE.computeIfAbsent(world, k -> new HashMap<>()).put(pos, player);
	}
}
